package cn.fldong.controller;

import cn.fldong.model.Student;
import cn.fldong.service.StudentService;
import cn.fldong.service.impl.StudentServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/students")
public class StudentServlet extends HttpServlet {
    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        studentService = new StudentServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        if (action == null) action = "list";

        try {
            switch (action) {
                case "list":
                    listStudents(request, response);
                    break;
                case "addPage":
                    request.getRequestDispatcher("/WEB-INF/views/student/add.jsp").forward(request, response);
                    break;
                case "add":
                    addStudent(request, response);
                    break;
                case "editPage":
                    editPage(request, response);
                    break;
                case "update":
                    updateStudent(request, response);
                    break;
                case "delete":
                    deleteStudent(request, response);
                    break;
                case "search":
                    searchStudents(request, response);
                    break;
                default:
                    listStudents(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(request, response);
        }
    }

    private void listStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        List<Student> students = studentService.getAllStudents();
        request.setAttribute("students", students);
        request.getRequestDispatcher("/WEB-INF/views/student/list.jsp").forward(request, response);
    }

    private void addStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String classId = request.getParameter("classId");
        String birthday = request.getParameter("birthday");
        String address = request.getParameter("address");
        Date obj1= Date.valueOf(birthday);
        if (studentService.studentIdExists(studentId)) {
            request.setAttribute("errorMsg", "学生ID已存在");
            Student student = new Student();
            student.setStudentId(studentId);
            student.setFullName(name);
            student.setGender(gender);
            student.setClassId(classId);

            student.setBirthDate(obj1);
            student.setAddress(address);
            request.setAttribute("student", student);
            request.getRequestDispatcher("/WEB-INF/views/student/add.jsp").forward(request, response);
            return;
        }

        Student student = new Student();
        student.setStudentId(studentId);
        student.setFullName(name);
        student.setGender(gender);
        student.setClassId(classId);
        Date obj= Date.valueOf(birthday);
        student.setBirthDate(obj);
        student.setAddress(address);

        boolean success = studentService.addStudent(student);
        if (success) {
            request.setAttribute("successMsg", "学生添加成功");
            listStudents(request, response);
        } else {
            request.setAttribute("errorMsg", "学生添加失败");
            request.setAttribute("student", student);
            request.getRequestDispatcher("/WEB-INF/views/student/add.jsp").forward(request, response);
        }
    }

    private void editPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String studentId = request.getParameter("studentId");
        Student student = studentService.getStudentById(studentId);
        request.setAttribute("student", student);
        request.getRequestDispatcher("/WEB-INF/views/student/edit.jsp").forward(request, response);
    }

    private void updateStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String gender = request.getParameter("gender");
        String classId = request.getParameter("classId");
        String birthday = request.getParameter("birthday");
        String address = request.getParameter("address");

        Student student = new Student();
        student.setStudentId(studentId);
        student.setFullName(name);
        student.setGender(gender);
        student.setClassId(classId);
        Date obj= Date.valueOf(birthday);
        student.setBirthDate(obj);
        student.setAddress(address);

        boolean success = studentService.updateStudent(student);
        if (success) {
            request.setAttribute("successMsg", "学生信息更新成功");
            listStudents(request, response);
        } else {
            request.setAttribute("errorMsg", "学生信息更新失败");
            request.setAttribute("student", student);
            request.getRequestDispatcher("/WEB-INF/views/student/edit.jsp").forward(request, response);
        }
    }

    private void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String studentId = request.getParameter("studentId");
        boolean success = studentService.deleteStudent(studentId);

        if (success) {
            request.setAttribute("successMsg", "学生删除成功");
        } else {
            request.setAttribute("errorMsg", "学生删除失败");
        }

        listStudents(request, response);
    }

    private void searchStudents(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String name = request.getParameter("name");
        String classId = request.getParameter("classId");

        List<Student> students;
        if (classId != null && !classId.isEmpty()) {
            students = studentService.getStudentsByClassId(classId);
        } else if (name != null && !name.isEmpty()) {
            students = studentService.getStudentsByName(name);
        } else {
            students = studentService.getAllStudents();
        }

        request.setAttribute("students", students);
        request.setAttribute("searchName", name);
        request.setAttribute("searchClassId", classId);
        request.getRequestDispatcher("/WEB-INF/views/student/list.jsp").forward(request, response);
    }
}